var mongodb = require('./db');

function Counter()
{
}
Counter.prototype.addData = function addData(jsonrecord, success,fail)
{
	//mongodb.close();
	//console.log("add data");
	mongodb.open( function(err,db){
		console.log("opendb");
		if(err){ console.log("fail"); return fail(err); }
		//read collection
		db.createCollection('record', function(err, col){ 
			db.collection('record',function(err,collection){
				console.log("open collection");
				if(err){ mongodb.close(); return fail(err); }
				//
				collection.findOne({sampleTimestamp:jsonrecord.sampleTimestamp},function(err,doc){
					if(doc)
					{						
						mongodb.close();
						return fail("record already exsit!");
					}
					else
					{						
						collection.insert(jsonrecord,{safe: true}, function(err, user){
							if(err){ mongodb.close(); return  fail(err); }
							mongodb.close();
							return success();
						});						
					}					
				});
			});
		});
	});
}
//
Counter.prototype.getAllData = function getAllData(success, fail)
{
	mongodb.open( function(err,db) {
		console.log("opendb");
		if(err){ console.log("fail"); return fail(err); }
		//read collection
		db.createCollection('record', function(err, col){ 
			db.collection('record',function(err,collection){
				console.log("open collection");
				if(err){ mongodb.close(); return fail(err); }
				//
				collection.find(function(err,cursor){
						if(err){ mongodb.close(); return fail(err); }
						cursor.toArray(function(err,items){
							if(err){ mongodb.close(); return fail(err); }
							mongodb.close();
							return success(items);							
						});
				});
			});
		});
	});
}

module.exports = new Counter();

